import fs from "fs";
import path from "path";
import archiver from "archiver";

export default function viteZipBuild(options = {}) {
  const defaultOptions = {
    zipName: "dist.zip",
    folderPath: "dist",
  };

  const finalOptions = { ...defaultOptions, ...options };
  return {
    name: "vite-plugin-zip-build",

    closeBundle: async () => {
      try {
        console.log("开始打包ZIP文件...");
        console.log("插件初始化配置:", finalOptions);

        const folderPath = path.resolve(process.cwd(), finalOptions.folderPath);
        const zipPath = path.resolve(folderPath, finalOptions.zipName);

        if (!fs.existsSync(folderPath)) {
          console.error(`❌ 目标文件夹 ${folderPath} 不存在！`);
          return;
        }

        const output = fs.createWriteStream(zipPath);
        const archive = archiver("zip", {
          zlib: { level: 9 },
        });

        output.on("close", () => {
          console.log(`✅ ZIP打包完成！`);
          console.log(`📦 输出路径: ${zipPath}`);
          console.log(
            `📊 文件大小: ${(archive.pointer() / 1024 / 1024).toFixed(2)} MB`
          );
        });

        archive.on("error", (err) => {
          console.error("❌ 打包过程出错:", err);
          throw err; // 抛出错误
        });

        archive.pipe(output);
        fs.readdirSync(folderPath).forEach((file) => {
          if (file !== finalOptions.zipName) {
            const filePath = path.join(folderPath, file);
            if (fs.statSync(filePath).isDirectory()) {
              archive.directory(filePath, file);
            } else {
              archive.file(filePath, { name: file });
            }
          }
        });

        await archive.finalize();
      } catch (error) {
        console.error("插件执行出错:", error);
      }
    },
  };
}
